from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from api_key import handler as api_key_handler
from api_key import get_api_key
import urllib
import hmac
import hashlib
import logging

def verify_api_sig(request_url, secret_key, api_sig):
    sig = hmac.new(secret_key, 
                   msg=request_url, 
                   digestmod=hashlib.sha1).hexdigest()
    logging.info(sig)
    return api_sig == sig

def check_request(request):
    #0. Read necessary parameter
    api_key = request.get('api_key')
    api_sig = request.get('api_sig')
    api = get_api_key(api_key)
    if (not api or not api_sig):
        return None
    #1. Remove api_sig
    param = dict (x.split('=')
                  for x in request.query_string.split('&'))
    del param['api_sig']
    #2. Sort all parameter
    tmp = param.items()
    tmp.sort()
    
    #3. Rebuild request
    query_string = '&'.join([k+'=' + urllib.quote(str(v))
                            for (k, v) in tmp])
    #4. Verify parameter
    verify_api_sig(request.path + '?' + query_string,
                    api.secret_key,
                    api_sig)
    return True

class HttpServices(webapp.RequestHandler):
    def common(self, request_handler, method):
        self.response.headers['Content-Type'] = 'application/json; charset=utf-8'
        if(not check_request(request_handler.request)):
            #failed
            self.response.out.write('{ "Class" : "IncorectSignature"}')
            pass
        #verified
        self.response.set_status(500)
        self.response.out.write('{ "Class" : "Successful"}')
        
    def post(self):
        self.common(self,'POST')
        pass
    def get(self):
        self.common(self,'GET')


application = webapp.WSGIApplication([
        ('/api_key/add', api_key_handler.AddApiKey),
        ('/bkitmobile/hello', HttpServices)
], debug=True)


def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()